/**
 * 
 */
package pers.vic.boot.util.json.fastjosn;

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SimplePropertyPreFilter;
import com.alibaba.fastjson.serializer.ValueFilter;

import pers.vic.boot.util.json.fastjosn.annotation.CustomerJsonField;

/**
 * @description: 只序列化指定属性,配合 @see CustomerJsonField注解使用, 支持单独对象和List<javaBean>
 * 获取json字符串:
 *  String json = JSONObject.toJSONString(javeBean, new CustomerPropertyFilter());
 * @author Vic.xu
 * @date: 2020年5月12日下午4:38:46
 */
public class CustomerPropertyFilter implements ValueFilter {

	private Field field = null;

	@Override
	public Object process(Object object, String name, Object value) {
		try {
			field = object.getClass().getDeclaredField(name);
			return handler(value);
		} catch (Exception e) {
			e.printStackTrace();
			return object;
		}
	}

	public <actualTypeArgument> Object handler(Object value) throws Exception {
		if (field == null || value == null) {
			return value;
		}
		//非CustomerJsonField注解 返回
		if (!field.isAnnotationPresent(CustomerJsonField.class)) {
			return value;
		}
		CustomerJsonField jsonField = field.getAnnotation(CustomerJsonField.class);
		// 把对象转换成只保留指定字段的JSON
		String json = JSONObject.toJSONString(value, new SimplePropertyPreFilter(jsonField.value()));
		
		// 如果数据是list,则根据泛型重构对象
		if (value instanceof List) {
			Type type = field.getGenericType();
			if (type instanceof ParameterizedType) {
				ParameterizedType parameterizedType = (ParameterizedType) type;
				// 泛型的真实class类型
				Class<?> actualTypeArgument = (Class<?>) parameterizedType.getActualTypeArguments()[0];
				if (actualTypeArgument != null) {
					Object obj = JSONObject.parseArray(json, actualTypeArgument);
					return obj;
				}
			}
		}
		// 普通对象
		Class<?> clazz = value.getClass();
		Object obj = JSONObject.parseObject(json, clazz);
		return obj;

	}

}
